﻿/*
 *
 * serial.c
 *
 *  Created on: 2017-08-03
 *      Author: chenshisheng
 */


#include "serial.h"

#define _RX_BUFFER_SIZE 20

struct _RxCtrl
{
    uint8_t buffer[_RX_BUFFER_SIZE];
    uint8_t size;
}_rxCtrl;

static Serial_FrameInCallback_t _onFrameIn;

void Serial_Init(Serial_FrameInCallback_t cb)
{
    _onFrameIn = cb;
    _rxCtrl.size = 0;

    /* UART2 configuration -------------------------------------------------*/
    CLK_PeripheralClockConfig(CLK_PERIPHERAL_UART2, ENABLE);

    /* UART2 configured as follow:
          - BaudRate = 9600 baud
          - Word Length = 8 Bits
          - One Stop Bit
          - No parity
          - Receive and transmit enabled
          - UART2 Clock disabled
     */
    /* Configure the UART2 */
    UART2_Init((uint32_t)9600, UART2_WORDLENGTH_8D, UART2_STOPBITS_1, UART2_PARITY_NO,
            UART2_SYNCMODE_CLOCK_DISABLE, UART2_MODE_TXRX_ENABLE);

    UART2_ClearFlag(UART2_FLAG_RXNE);

    /* Enable UART2 Receive interrupt*/
    UART2_ITConfig(UART2_IT_RXNE_OR, ENABLE);
}

void Serial_RxIrs(void)
{
    uint8_t b;

    Main_SetTimerCounter(Main_Timer_Rx, 20);
    b = UART2_ReceiveData8();
    if(_rxCtrl.size < _RX_BUFFER_SIZE)
    {
        _rxCtrl.buffer[_rxCtrl.size] = b;
        _rxCtrl.size ++;
    }
}

int8_t Serial_SendCompleted(void)
{
    return UART2_GetFlagStatus(UART2_FLAG_TC) == SET;
}

void Serial_SendByte(uint8_t b)
{
    UART2_SendData8(b);

    /* Loop until the end of transmission */
    while (UART2_GetFlagStatus(UART2_FLAG_TXE) == RESET);
}

void Serial_Send(const void *data, unsigned int size)
{
    const uint8_t *vdata;

    vdata = (const uint8_t *) data;
    while(size--)
    {
        Serial_SendByte(*vdata++);
    }
}

void Serial_OnFrameIn(void)
{
    _onFrameIn(_rxCtrl.buffer, _rxCtrl.size);
    _rxCtrl.size = 0;
}
